package edu.ccut.saturn.studio.wfg.dialog.userdialog;

import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.TableItem;

import edu.ccut.saturn.studio.wfg.dialog.SelectionCandidate;
import edu.ccut.saturn.studio.wfg.wfgmodel.UsersAttribute;

public class MyCellModifierUsersAttribute implements ICellModifier{
	
	private TableViewer tableViewer;
	
	public MyCellModifierUsersAttribute(TableViewer tableViewer){
		this.tableViewer = tableViewer;
	}

	public boolean canModify(Object element, String property) {
		return true;
	}

	public Object getValue(Object element, String property) {
		UsersAttribute o = (UsersAttribute) element;
		if (property.equals("id")) {
			return o.getId();
		} else if(property.equals("name")){
			return o.getName();
		} else if(property.equals("type")){
			return getTypeIndex(o.getType());
		}
		throw new RuntimeException("" + property); 
	}
	
	private int getTypeIndex(String type){
		for(int i = 0; i < SelectionCandidate.userTypes.length; i++){
			if(SelectionCandidate.userTypes[i].equals(type)){
				return i;
			}
		}
		return -1;
	}

	public void modify(Object element, String property, Object value) {
		TableItem item = (TableItem) element;
		UsersAttribute o = (UsersAttribute) item.getData();
		if(property.equals("id")){
			String newID = (String) value;
			o.setId(newID);
		} else if(property.equals("name")){
			String newName = (String) value;
			o.setName(newName);
		} else if(property.equals("type")){
			Integer comboIndex = (Integer) value;
			String newType = SelectionCandidate.userTypes[comboIndex];
			o.setType(newType);
		} else {
			throw new RuntimeException("" + property); 
		}
		
		tableViewer.update(o, null);
	}
}
